package cn.line5.seam.util;

import java.lang.reflect.Field;

import cn.line5.seam.exception.SeamException;

/**
 * <h1>反射操作工具类</h1>
 * 
 * @author liuxj
 * @since JDK1.6
 */
public class ReflectUtil {

	/**
	 * 将字段内容写入对象字段中，允许写入private、protected、public等。但是如果字段定义为final将抛出异常。
	 * 
	 * @param fieldName
	 *            字段名称
	 * @param o
	 *            要写入的对象
	 * @param value
	 *            要写入的内容
	 * @throws SeamException
	 *             字段在对象中不存在、不允许写入、类型不匹配时将抛出异常
	 */
	public static void setFieldValue(String fieldName, Object o, Object value)
			throws SeamException {
		try {
			Field f = o.getClass().getDeclaredField(fieldName);
			f.setAccessible(true);
			f.set(o, value);
		} catch (SecurityException e) {
			throw new SeamException("The field '" + fieldName
					+ "' read or write error in the class "
					+ o.getClass().getName() + ".", e);
		} catch (IllegalArgumentException e) {
			throw new SeamException("The field '" + fieldName
					+ "' read or write error in the class "
					+ o.getClass().getName() + ".", e);
		} catch (NoSuchFieldException e) {
			throw new SeamException("The field '" + fieldName
					+ "' read or write error in the class "
					+ o.getClass().getName() + ".", e);
		} catch (IllegalAccessException e) {
			throw new SeamException("The field '" + fieldName
					+ "' read or write error in the class "
					+ o.getClass().getName() + ".", e);
		}
	}
}